(function (window, $, undefined) {

	$.util.namespace("mainpage");
	$.util.namespace("mainpage.mainTabs");
	
	var homePageTitle = "主页", mainLayout = "#mainLayout", northLayout = "#northLayout", westLayout = "#westLayout", centerLayout = "#centerLayout",
		eastLayout = "#eastLayout", southLayout = "#southLayout",
		navMenus = "#navMenus", navPanel = "#navPanel", mainTabs = "#mainTabs" ;
	
	
	//菜单
	window.mainpage.loadNavMenus = function() {
		var ul = $("#navMenus").empty() ;
		$.get($.ctx+"/assets/json/nav-menu.json", function(menus){
			
			$.each(window.mainpage.navMenusData = menus, function(i, p) {
				var li = $("<li></li>").appendTo(ul);
				var a = $("<a></a>")
				.addClass((p.selected?"selected":""))
				.html("<i class='"+p.icon+"'></i>" + p.text)
				.click(function(){
					if(a.is(".selected") || a.attr("disabled")) {return;}
					ul.find("a").removeClass("selected");
					a.addClass("selected");
					
					window.mainpage.loadMenuTree({"id": p.id, "text": p.text});
				}).appendTo(li);
			});
			
			var layout = $(westLayout),
				south = layout.layout("panel", "south"),
				southOpts = south.panel("options"),
				navHeight = 32;
			southOpts.minHeight = (menus.length+3) + (Math.min(menus.length, 5) * navHeight) ;
			southOpts.maxHeight = (menus.length+3) + (menus.length * navHeight) ;
			layout.layout("resize");
			
			$.each(window.mainpage.navMenusData, function(i, p){
				if(p.selected) {
					if(p.mode == "tree") {
						var selectedMenu = $("#navMenus").find("a.selected");
						window.mainpage.loadMenuTree(p);
					}
				}
			});
			 
		}, "JSON");
	};
	
	//给tree添加数据
	window.mainpage.loadMenuTree = function(opts) {
		var menutree = $("#menuTree") ;
		var root = opts;
		$.get($.ctx+"/assets/json/nav-tree.json", function(tree){
			root.children = tree;
			menutree.tree("loadData", [root]);
		}, "JSON");
	};
	//初始化tree
	window.mainpage.initMenuTree = function() {
		var navBox = $(navPanel);
		var ul = $("<ul></ul>").attr("id", "menuTree").appendTo(navBox);
		ul.tree({
			lines: true,
			animate: true,
            onClick: function (node) {
            	window.mainpage.mainTabs.addModuleTab(node);
            },
            onLoadSuccess: function (node, data) {
            }
		});
	};
	//初始化菜单
	window.mainpage.instMainMenus = function() {
		//加载NavMenus菜单
		window.mainpage.loadNavMenus();
		//创建easyui tree控件
		window.mainpage.initMenuTree();
	};
	
	
	window.mainpage.mainTabs.addModuleTab = function (node) {
        var n = node || {}, attrs = node.attributes || {}, opts = $.extend({}, n, { title: n.text }, attrs);
        if (!opts.href) { return; }
        window.mainpage.mainTabs.addModule(opts);
    };
    
	window.mainpage.mainTabs.addModule = function (title, href, iconCls, iniframe, closable, refreshable, selected) {
		var opts = window.mainpage.mainTabs.parseCreateTabArgs(arguments), isExists = window.mainpage.mainTabs.isExists(opts.title, opts.href);
		switch (isExists) {
	        case 0: window.mainpage.mainTabs.createTab(opts); break;
	        case 1: window.mainpage.mainTabs.select(opts); break;
	        default: break;
    	}
	};
	window.mainpage.mainTabs.createTab = function(title, href, iconCls, iniframe, closable, refreshable, selected) {
		var t = $(mainTabs), opts = window.mainpage.mainTabs.parseCreateTabArgs(arguments);
		
		var exts = {} ; exts.href = opts.href; exts.content = opts.content;
		
        opts.href = null;
        opts.content = "<iframe src=\"\" class=\"panel-iframe\" frameborder=\"0\" width=\"100%\" height=\"100%\" marginwidth=\"0px\" marginheight=\"0px\" scrolling=\"auto\"></iframe>";
		
		t.tabs("add", opts);
		
		var tp = t.tabs("getTab", opts.title) ;
		tp.panel("body").css("overflow", "hidden");
		
		var iframe = tp.panel("body").children("iframe.panel-iframe") ;
		iframe.bind({
			load: function () {
            },
            error: function () {
            }
		}).attr("src", $.ctx+"/demo/main");
		
		
	};
	window.mainpage.mainTabs.tabDefaultOption = {
		title: "新建选显卡", href: "", iniframe: true, closable: true, tools: [{iconCls:'icon-mini-refresh',handler:function(){$(mainTabs).tabs("refresh");}}]
	};
	window.mainpage.mainTabs.parseCreateTabArgs = function (args) {
		var ret = {};
        if (!args || !args.length) {
            $.extend(ret, window.mainpage.mainTabs.tabDefaultOption);
        } else if (args.length == 1) {
            $.extend(ret, window.mainpage.mainTabs.tabDefaultOption, typeof args[0] == "object" ? args[0] : { href: args[0] });
        } else if (args.length == 2) {
            $.extend(ret, window.mainpage.mainTabs.tabDefaultOption, { title: args[0], href: args[1] });
        } else if (args.length == 3) {
            $.extend(ret, window.mainpage.mainTabs.tabDefaultOption, { title: args[0], href: args[1], iconCls: args[2] });
        } else if (args.length == 4) {
            $.extend(ret, window.mainpage.mainTabs.tabDefaultOption, { title: args[0], href: args[1], iconCls: args[2], iniframe: args[3] });
        } else if (args.length == 5) {
            $.extend(ret, window.mainpage.mainTabs.tabDefaultOption, { title: args[0], href: args[1], iconCls: args[2], iniframe: args[3], closable: args[4] });
        } else if (args.length == 6) {
            $.extend(ret, window.mainpage.mainTabs.tabDefaultOption, { title: args[0], href: args[1], iconCls: args[2], iniframe: args[3], closable: args[4], refreshable: args[5] });
        } else if (args.length >= 7) {
            $.extend(ret, window.mainpage.mainTabs.tabDefaultOption, { title: args[0], href: args[1], iconCls: args[2], iniframe: args[3], closable: args[4], refreshable: args[5], selected: args[6] });
        }
        return ret;
    };
	//  判断指定的选项卡是否存在于当前主页面的选项卡组中；
    //  返回值：返回的值可能是以下几种：
    //      0:  表示不存在于当前选项卡组中；
    //      1:  表示仅 title 值存在于当前选项卡组中；
    //      2:  表示 title 和 href 都存在于当前选项卡组中；
    window.mainpage.mainTabs.isExists = function (title, href) {
    	var t = $(mainTabs), tabs = t.tabs("tabs"), ret = 0 ;
    	$.each(tabs, function(i, e) {
    		var opts = e.panel("options") ;
    		if(opts.title == title) {
    			ret = 1;
    			return true;
    		} 
    	});
    	return ret ;
    };
    
    window.mainpage.mainTabs.select = function (opts) { $(mainTabs).tabs("select", opts.title); };
    
    window.mainpage.mainTabs.jumpHome = function () { $(mainTabs).tabs("select", homePageTitle) }
    window.mainpage.mainTabs.closeAllTabs = function () {
    	$(mainTabs).tabs("closeAll");
    };
    window.mainpage.togglePanels = function () { 
    	console.info();
    	var l = $(mainLayout) ;
    	var regions = ["north", "west", "east", "south"] ;
    	$.each(regions, function() {
    		var p = l.layout("panel", this);
    		
    		var opts = p.panel("options");
            if (opts.collapsed) { l.layout("expand", this); } else { l.layout("collapse", this); }
    	});
    	window.setTimeout(function(){
    		l.layout("resize");
    	}, 500);
    	
    };
    window.mainpage.mainTabs.jumpTab = function (which) { $(mainTabs).tabs("jumpTab", which); };
	
    
    window.mainpage.hideNorth = function () { $(mainLayout).layout("collapse", "north"); };
    window.mainpage.hideWest = function () { $(mainLayout).layout("collapse", "west"); };
    window.mainpage.hideEast = function () { $(mainLayout).layout("collapse", "east"); };
    
    window.mainpage.bindMainTabsButtonEvent = function () {
        $("#mainTabs_jumpHome").click(function () { window.mainpage.mainTabs.jumpHome(); });
        $("#mainTabs_toggleAll").click(function () { window.mainpage.togglePanels(); });
        $("#mainTabs_jumpTab").click(function () { window.mainpage.mainTabs.jumpTab(); });
        $("#mainTabs_closeAll").click(function () { window.mainpage.mainTabs.closeAllTabs(); });
    };
    window.mainpage.bindToolbarButtonEvent = function () {
    	$("#btnHideNorth").click(function () { window.mainpage.hideNorth(); });
    	$("#btnHideWest").click(function () { window.mainpage.hideWest(); });
        $("#btnHideEast").click(function () { window.mainpage.hideEast(); });
    };
    
    /*var panelOptions = $.fn.tabs.extensions.panelOptions = $.extend({}, $.fn.panel.defaults, {

        //  该选项卡的 href 是否在 iframe 中打开。
        iniframe: false,

        //  该选项卡是否具有重复打开功能
        repeatable: false,

        //  该选项卡是否具有刷新功能。
        refreshable: true,

        //  双击选项卡标题是否能将其关闭，当该选项卡 closable: true 时，该属性有效。
        closeOnDblClick: true,

        href: null,

        iconCls: "icon-standard-application-form"
    });*/
    
    $.extend($.fn.panel.defaults, {
    	
    });
    //扩展 easyui-tabs 插件 关闭标签页方法
    $.extend($.fn.tabs.methods,{
        allTabs:function(jq){
            var tabs = $(jq).tabs('tabs');
            var all = [];
            all = $.map(tabs,function(n,i){
                 return $(n).panel('options')
            });
            return all;
        },
        closeCurrent: function(jq){ // 关闭当前
            var currentTab = $(jq).tabs('getSelected'),
                currentTabIndex = $(jq).tabs('getTabIndex',currentTab);
             $(jq).tabs('close',currentTabIndex);
        },
        closeAll:function(jq){ //关闭全部
            var tabs = $(jq).tabs('allTabs');
            $.each(tabs,function(i,n){
            	if(i>0){//主页不关闭
            		$(jq).tabs('close', n.title);
            	}
            })
        },
        closeOther:function(jq){ //关闭除当前标签页外的tab页
            var tabs =$(jq).tabs('allTabs');
            var currentTab = $(jq).tabs('getSelected'),
                currentTabIndex = $(jq).tabs('getTabIndex',currentTab);
     
            $.each(tabs,function(i,n){
                if(currentTabIndex != i) {
                    $(jq).tabs('close', n.title);
                }
            })
        },
        closeLeft:function(jq){ // 关闭当前页左侧tab页
            var tabs = $(jq).tabs('allTabs');
            var currentTab = $(jq).tabs('getSelected'),
                currentTabIndex = $(jq).tabs('getTabIndex',currentTab);
            var i = currentTabIndex-1;
     
            while(i > -1){
                $(jq).tabs('close', tabs[i].title);
                i--;
            }
        },
        closeRight: function(jq){ // 关闭当前页右侧tab页
            var tabs = $(jq).tabs('allTabs');
            var currentTab = $(jq).tabs('getSelected'),
                currentTabIndex = $(jq).tabs('getTabIndex',currentTab);
            var i = currentTabIndex+ 1,len = tabs.length;
            while(i < len){
                $(jq).tabs('close', tabs[i].title);
                i++;
            }
        },
        jumpTab: function (jq, which) {
        	jq.each(function () {
        		var t = $(this), tab = (which == null || which == undefined) ? t.tabs("getSelected") : t.tabs("getTab", which), opts = tab.panel("options");
        		var href = tab.panel("body").children("iframe.panel-iframe").attr("src") ;
        		if (href && opts.iniframe) {
        			window.open(href, "_blank");
        		}
        	})
        },
        refresh: function (jq, which) {
        	jq.each(function () {
        		var t = $(this), tab = (which == null || which == undefined) ? t.tabs("getSelected") : t.tabs("getTab", which), opts = tab.panel("options");
        		var iframe = tab.panel("body").children("iframe.panel-iframe") ;
        		iframe.attr("src", iframe.attr("src"));
        	})
        }
    })
	
	$(function() {
		window.mainpage.instMainMenus();
		window.mainpage.bindMainTabsButtonEvent();
		window.mainpage.bindToolbarButtonEvent();
	});
	
})(window, jQuery);